package com.itheima.service.impl;

import com.itheima.service.CreateCodeService;
import com.itheima.utils.MailUtils;
import com.itheima.utils.UuidUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Author: Felix(李鑫)
 * @Date: 2020/8/29 11:26
 * @Description:  根据手机号或者邮箱发送验证码
 */

@Service
public class CreateCodeServiceImpl implements CreateCodeService {

    /**
     * 正则表达式：验证手机号
     */
    public static final String REGEX_MOBILE = "^((17[0-9])|(14[0-9])|(13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$";
    /**
     * 正则表达式：验证邮箱
     */
    public static final String REGEX_EMAIL = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";


    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public boolean sendCode(String info) {

        //判断传来的数据是否符合规范
        if (info == null) {
            return false;
        }

        //发送验证码到手机
        if (Pattern.compile(REGEX_MOBILE).matcher(info).matches()){
            //todo: 手机发送功能待完善
            return false;
        }

        //发送验证码到邮箱
        if (Pattern.compile(REGEX_EMAIL).matcher(info).matches()){
            //根据用户信息将生成的验证码存入redis中
            String validCode = UuidUtil.getUuid();
            redisTemplate.boundHashOps("ValidCode").put(info, validCode);

            //发送验证码到指定的邮箱中
            MailUtils.sendMail(info,"激活码: " + validCode,"实战博客验证码");//todo: 激活验证码发往到邮件中
            return true;
        }


        return false;
    }

}
